package com.donger.common.data.tenant;


import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.donger.common.security.service.UserDetail;
import com.donger.common.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class BootTenantHandler implements TenantHandler {

    @Autowired
    private TenantConfigProperties properties;


    @Override
    public Expression getTenantId() {
        Long tenantId = SecurityUtil.getCurrentUserLogin().map(UserDetail::getTenantId).orElse(null);
        log.debug("获取用户中的租户id -> {}",tenantId);
        if(tenantId == null){
            return new NullValue();
        }
        return new LongValue(tenantId);
    }

    /**
     * 获取租户id 字段名
     * @return
     */
    @Override
    public String getTenantIdColumn() {
        return properties.getColumn();
    }

    /**
     * 根据表名判断是否进行过滤
     * @param tableName
     * @return
     */
    @Override
    public boolean doTableFilter(String tableName) {


        Long tenantId = SecurityUtil.getCurrentUserLogin().map(UserDetail::getTenantId).orElse(null);
        log.debug("租户中的ID -》 {}",tenantId);

//        return Boolean.FALSE;
        // 租户id为空则查询全部
        if(tenantId == null){
            return Boolean.TRUE;
        }

//        return Boolean.FALSE;
        return !properties.getTables().contains(tableName);
    }
}
